<?php 

class BaiduVoice{

	private $appid  = '2106133';
	private $appkey = 'vjM3z13U4avU3W0Ex86ZUONA';
	private $appsecret = 'Q9PjFE2rtjRlViUXZNt9bb1b8yZ5iAbr';

	//access_token 存储文件
	static $file = './access_token.json';
	//音频存储文件夹
	static $fileRoot = './';
	//文本内容
	static private $text = '';
	//文本长度
	static private $strlen = null;
	//accesstoken
	static private $access_token = null;
	//文件存储类型：0 直接跳转到网页，1 以mp3格式存储文件
	static $fileType = 1;
	//是否分割文本： 0 否 1 是 在文本超过1024字节时，如果需要输出完整文本请选择分割，当$fileType=0时无法进行分割.
	static $cut = 0;
	//临时文本
	static private $textTemp = array();
	//文本长度
	static $textNum = 524;
	//配置
	public $config = array(
					'lan' => 'zh',
					'tok' => '',   //access token
					'ctp' => 1,
					'cuid'=> 'bc:5f:f4:e2:7d:1f',
					'spd' => 5,
					'pit' => 5,
					'vol' => 5,
					'per' => 0,
					'tex' => ''  //文本内容
					);

	public function getText ($data) {

		if (empty($data)) {
			return $this->getError("002","文本不能为空");
		}

		self::$text = $this->DeleteHtml($data);

		if (!$this->checkCoding()) {
			return $this->getError('004','文本编码只能是UTF-8');
		}

		if (!$this->getToken()) {
			return $this->getError('003','获取AccessToken失败');
		}	

		if (self::$cut && self::$fileType == 1) {
			
			$this->textCut();
			
			return $this->putArrayApi();


		}else{
			
			return $this->putApi();

		}
		
		
	}
	/**
	 * [putArrayApi 多文件生成]
	 * @return [type] [description]
	 */
	private function putArrayApi () {

		$config = $this->config;
		$config['tok'] = self::$access_token;

		$text = self::$textTemp;
			
		$filename = array();
		foreach ($text as $value) {
			$config['tex'] = $value;
			$filename[] = $this->putMediaFile($config);			
		}
		return $filename;
	}
	/**
	 * [putApi 单文件生成]
	 * @return [type] [description]
	 */
	private function putApi () {
				
		$config = $this->config;
		$config['tok'] = self::$access_token;
		$config['tex'] = self::$text;


		if (self::$fileType) {
			return $this->putMediaFile($config);
		}else{
			return $this->getMedia($config);
		}

	}

	/**
	 * [textCut 文本截取]
	 * @return [type] [description]
	 */
	private function textCut () {
		$num = self::$textNum;
		//$leng = strlen(self::$text);
		$leng = $this->checkLength();
		$total = ceil($leng / $num);
		$page = 0;
		$topage = $num;

		$text = self::$text;
		$textTemp = array();
				
		self::$textTemp = str_split($text,1521);
		return true;


	}


	/**
	 * [getMedia url访问]
	 * @param  [arrsy] $data [description]
	 * @return [type]       [description]
	 */
	private function getMedia ($data) {

		$url = 'http://tsn.baidu.com/text2audio?'.$this->toUrlPam($data);
		Header("location:$url");
		exit;
	}

	/**
	 * [putMediaFile 生成文件]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function putMediaFile ($data) {


		$url = 'http://tsn.baidu.com/text2audio';
		$sign = $this->toUrlPam($data);
		$result = self::https_post($url,$sign);
				
		$status = json_decode($result,true);

		if (isset($status['err_no']) || $status['err_msg']) {
			$error = "ERROR:".$status['err_no'].";msg:".$status['err_msg'];
			return $this->getError(006,$error);
		}

		$filename = self::$fileRoot.time().".mp3";

		$this->setFile($filename,$result);

		return $filename;
	}

	/**
	 * [DeleteHtml 清除空格换行]
	 * @param [type] $str [description]
	 */
	private function DeleteHtml($str) 
		{ 
		 $search = array(" ","　","\n","\r","\t");
    	 $replace = array("","","","","");
		 return str_replace($search, $replace, $str);
		}

	/**
	 * [toUrlPam 拼接URL]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function toUrlPam ($data) {
		$str = '';
		foreach ($data as $key=>$value) {
			$str .= $key.'='.$value."&";
		}
		$str = rtrim($str,"&");
		return $str;
	}

	/**
	 * [getToken ]
	 * @return [type] [description]
	 */
	private function getToken () {

		$accesstoken = $this->getFile();
		$accesstoken = json_decode($accesstoken,true);

		if (empty($accesstoken) || (time() - $accesstoken['addtime']) >= $accesstoken['expires_in']) {
			$this->PutAccessToken();
			return 	$this->getToken();		
		}

		self::$access_token = $accesstoken['access_token'];
		return true;
	}


	/**
	 * [getAccessToken 获取AccessToken]
	 * @return [bool] [成功返回bool]
	 */
	private function PutAccessToken () {

		$url = 'https://openapi.baidu.com/oauth/2.0/token';

		$data['grant_type'] = 'client_credentials';

		$data['client_id'] = $this->appkey;
		$data['client_secret'] = $this->appsecret;

		$result = self::https_post($url,$data);
		
		$status = json_decode($result,true);

		if ($status['access_token']) {

			$status['addtime'] = time();

			$this->setFile(self::$file,json_encode($status));

			return true;

		}else{
			return $this->getError('003','获取AccessToken失败');
		}

	}

	/**
	 * [checkCoding 检查是否为utf8编码]
	 * @return [type] [description]
	 */
	private function checkCoding () {
		if (mb_detect_encoding(self::$text,array('UTF-8','ASCII'))) {
			return true;
		}
	}
	/**
	 * [checkLength 检查长度]
	 * @return [type] [description]
	 */
	private function checkLength () {
			return self::$strlen = mb_strlen(self::$text,"UTF-8");
	}
	

	/**
	 * [setFile 写入文件]
	 * @param [type] $data [description]
	 */
	private function setFile($fliename,$data) {
		$fp = fopen($fliename,'w+');
		fwrite($fp,$data);
		fclose($fp);
		
	}
	/**
	 * [getFile 读取文件]
	 * @return [type] [description]
	 */
	private function getFile () {
		return file_get_contents(self::$file);
	}


	/**
	 * [getError 抛出错误]
	 * @param  integer $status [description]
	 * @param  [type]  $msg    [description]
	 * @return [type]          [description]
	 */
	private function getError($status = 002,$msg=null){
		$newArray = array(
				'status' => $status,
				'msg' => $msg
			);
		echo json_encode($newArray);exit;
	}

	/**
	 * [https_post CURL发送]
	 * @param  [staring] $url  [description]
	 * @param  [string OR array ] $data [description]
	 * @return [objet]       [description]
	 */
	private static function https_post ($url,$data = null) {
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        //添加
        curl_setopt($curl,CURLOPT_REFERER,"http://www.baidu.com");  //构造来路
        //结束
        if (!empty($data)) {
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }






}